/*
 *
 * Copyright 2014 CDSF Corporation, Inc. All rights reserved.
 */
package com.sefonsoft.dataanalysis.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.alibaba.fastjson.parser.DefaultJSONParser;


public abstract class Tools {
	

	/**
	 * 判断参数是否为空，不为空返回false, 为空返回true
	 *
	 * @author wangshuang
	 * @creaetime Jun 16, 2014 2:29:06 PM
	 * @param obj 判断参数
	 * @return a boolean.
	 */
	public static boolean isNotNull(Object obj) {
		return obj != null && !"null".equals(obj) && !"".equals(obj);
	}

	/**
	 * <p>
	 * isNull.
	 * </p>
	 *
	 * @param str a {@link java.lang.String} object.
	 * @return a boolean.
	 */
	public static boolean isNull(String str) {
		return str == null || "".equals(str.trim());
	}

	/**
	 * <p>
	 * isNotNull.
	 * </p>
	 *
	 * @param str a {@link java.lang.String} object.
	 * @return a boolean.
	 */
	public static boolean isNotNull(String str) {
		return str != null && !"".equals(str.trim());
	}

	/**
	 * <p>
	 * isEmpty.
	 * </p>
	 *
	 * @param array an array of {@link java.lang.Object} objects.
	 * @return a boolean.
	 */
	public static boolean isEmpty(Object[] array) {
		return array == null || array.length == 0;
	}

	/**
	 * <p>
	 * isNotEmpty.
	 * </p>
	 *
	 * @param array an array of {@link java.lang.Object} objects.
	 * @return a boolean.
	 */
	public static boolean isNotEmpty(Object[] array) {
		return array != null && array.length > 0;
	}

	/**
	 * <p>
	 * isEmpty.
	 * </p>
	 *
	 * @param list a {@link java.util.List} object.
	 * @return a boolean.
	 */
	public static boolean isEmpty(List<?> list) {
		if (list == null || list.isEmpty()) {
			return true;
		}
		return false;
	}

	/**
	 * 判断参数是否为空，为空返回ture, 不为空返回false
	 *
	 * @author wangshuang
	 * @creaetime Jun 23, 2014 9:10:23 AM
	 * @param obj 待判断参数
	 * @return a boolean.
	 */
	public static boolean isNull(Object obj) {
		return obj == null || "null".equals(obj);
	}
	
	/**
	 * 判断参数是否为空或者undefined，为空返回ture, 不为空返回false
	 *
	 * @author xgj
	 * @creaetime 2017年9月19日11:14:49
	 * @param str 待判断参数
	 * @return a boolean.
	 */
	public static boolean isNullOrUndefined(String str) {
		return str == null || "".equals(str.trim()) || "null".equals(str) || "undefined".equals(str);
	}

	/**
	 * 方法描述：格式化时间为字符串
	 *
	 * @creator ZhengQiu
	 * @param time a {@link java.util.Date} object.
	 * @param type a int.
	 * @return a {@link java.lang.String} object.
	 */
	public static String formatDateToStr(int type, Date time) {
		if (time == null) {
			return "";
		}
		String format = getPattern(type);
		return new SimpleDateFormat(format).format(Long.valueOf(time.getTime()));
	}

	/**
	 * 格式化字符串为时间
	 *
	 * @param type a int.
	 * @param time a {@link java.lang.String} object.
	 * @throws java.text.ParseException if any.
	 * @return a {@link java.util.Date} object.
	 */
	public static Date formateStrToDate(int type, String time) throws ParseException {
		if (Tools.isNull(time)) {
			return null;
		}
		String format = getPattern(type);
		return new SimpleDateFormat(format).parse(time);
	}

	/**
	 * <p>
	 * getPattern.
	 * </p>
	 *
	 * @param formatIndex a int.
	 * @return a {@link java.lang.String} object.
	 */
	public static String getPattern(int formatIndex) {
		String format = null;
		switch (formatIndex) {
			case -2:
				format = "HH:mm:ss.S";
				break;
			case -1:
				format = "yyyy-MM-dd HH:mm:ss.S";
				break;
			case 0:
				format = "yyyy-MM-dd HH:mm:ss";
				break;
			case 1:
				format = "yyyy-MM-dd 00:00:00";
				break;
			case 2:
				format = "yyyy-MM-dd 23:59:59";
				break;
			case 3:
				format = "yyyy-MM-dd";
				break;
			case 4:
				format = "yyyy-MM";
				break;
			case 5:
				format = "yyyy-MM-dd HH:mm:ss";
				break;
			case 6:
				format = "yyyy-01-01 00:00:00";
				break;
			case 7:
				format = "yyyy-12-31 23:59:59";
				break;
			case 8:
				format = "yyyy-MM-01 00:00:00";
				break;
			case 10:
				format = "yyyyMMddHHmmss";
				break;
			case 11:
				format = "yyyyMMddHHmmssS";
				break;
			case 12:
				format = "yyyy年MM月dd日";
				break;
			case 13:
				format = "yyyyMMdd-HHmmssS";
				break;
			case 14:
				format = "yyyy年MM月dd日HH时mm分ss秒";
				break;
			case 15:
				format = "yyyy-MM-dd HHmmss";
				break;
			default:
				format = "yyyy-MM-dd HH:mm:ss";
		}
		return format;
	}

	/**
	 * 拼装删除字符串
	 *
	 * @author wangshuang
	 * @creaetime Jul 1, 2014 3:33:29 PM
	 * @param object a {@link java.lang.Object} object.
	 * @return a {@link java.util.List} object.
	 */
	// public static List<String> getFlowIds(Object object) {
	// String flowIds = String.valueOf(object);
	// String[] split = flowIds.split(Constants.COMMA);
	// return Arrays.asList(split);
	// }

	/**
	 * 创建uuid
	 *
	 * @author wangshuang
	 * @creaetime Jul 2, 2014 6:12:50 PM
	 * @return a {@link java.lang.String} object.
	 */
	public static String createUUID() {
		return UUID.randomUUID().toString().replace("-", "");
	}

	/**
	 * 获取通用格式时间对象
	 *
	 * @author CodingBoy
	 * @creaetime 2014年7月18日 上午9:18:29
	 * @throws java.text.ParseException if any.
	 * @return a {@link java.util.Date} object.
	 */
	public static Date getCommonDate() throws ParseException {
		return Tools.formateStrToDate(0, Tools.formatDateToStr(0, new Date()));
	}

	/**
	 * <p>
	 * startTimeLowerThanEndTime.
	 * </p>
	 *
	 * @author wangshuang
	 * @creaetime Aug 4, 2014 3:50:04 PM
	 * @param type a int.
	 * @param startDate a {@link java.lang.String} object.
	 * @param endDate a {@link java.lang.String} object.
	 * @throws java.text.ParseException if any.
	 * @return a boolean.
	 */
	public static boolean startTimeLowerThanEndTime(int type, String startDate, String endDate) throws ParseException {
		Date startD = Tools.formateStrToDate(type, startDate);
		Date endD = Tools.formateStrToDate(type, endDate);
		if (startD.getTime() > endD.getTime()) {
			return true;
		}
		return false;
	}

	/**
	 * 方法描述：TODO
	 *
	 * @creator(methods创建人) CodingBoy
	 * @creaetime(生成日期) 2014年8月27日 上午11:03:35
	 * @return a {@link java.lang.String} object.
	 */
	public static String createProcessCode() {
		String ap = "0123456789QWERTYUIOPLKJHGFDSAZXCVBNM";
		char[] charArray = ap.toCharArray();
		Random r = new Random();
		int nextInt = 0;
		String code = "";
		for (int i = 0; i < 8; i++) {
			nextInt = r.nextInt(ap.length());
			code = code + charArray[nextInt];
		}
		return code + "-" + System.currentTimeMillis();
	}

	// public void sortUserByPingyin(List<User> users) {
	// Comparator<Object> com1 = new Comparator<Object>() {
	// @Override
	// public int compare(Object o1, Object o2) {
	// Comparator<Object> com = Collator
	// .getInstance(java.util.Locale.CHINA);
	// User user1 = (User) o1;
	// User user2 = (User) o2;
	//// return com.compare(user1.getUserName(), user2.getName());
	// return 1;
	// }
	// };
	// Collections.sort(users, com1);
	// }

	/**
	 * 获取x~y范围内的随机数
	 * @param x
	 * @param y
	 * @return
	 */
	// public static int getRandomInt(int x,int y){
	// return RandomUtils.nextInt(y-x)+x;
	// }

	/**
	 * 验证手机号是否正确
	 * @param mobiles
	 * @return
	 */
	public static boolean isMobileNO(String mobiles) {
		Pattern p = Pattern.compile("^((17[0-9])|(13[0-9])|(15[^4,\\D])|(18[0-9]))\\d{8}$");
		Matcher m = p.matcher(mobiles);
		return m.matches();
	}

	private static Random random = new Random();

	/**
	 * 从 min 和 max 中间随机一个值（包含min max）
	 * 
	 * @param min
	 * @param max
	 * @return
	 */
	public static int random(int min, int max) {
		if (max - min <= 0)
			return min;
		return min + random.nextInt(max - min + 1);
	}

	/**
	 * 读取properties配置文件信息
	 * @Author zhangwen
	 * @Date 2016/12/13 10:00
	 */
	public static Map<String, String> getPropertyFile(String fileName) {
		Map<String, String> map = new HashMap<String, String>();
		ResourceBundle resurce = ResourceBundle.getBundle(fileName);
		Set<String> keys = resurce.keySet();
		for (String key : keys) {
			map.put(key, resurce.getString(key).trim());
		}
		return map;
	}

	/**
	 * @Descrption : 创建当前时间戳 yyyy-MM-dd HH:mm:ss
	 * @Author zhangwen
	 * @Date 2017/4/11/ 15:30
	 */
	public static String createNowTimeStamp() {
		return formatDateToStr(0, new Date());
	}
	
	/**
	 * 
	 * @author yangjiangsong
	 * @param date
	 * @return
	 */
	public static String format(Date date){
		if(null == date){
			return "";
		}
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	    String dateString = formatter.format(date);
	    return dateString;
	}
	
	/**
	 * 时间格式转中文
	 * @author xgj
	 * @param date
	 * @return
	 */
	public static String formatToChinese(Date date){
		if(null == date){
			return "";
		}
		SimpleDateFormat formatter = new SimpleDateFormat(getPattern(14));
		String dateString = formatter.format(date);
		return dateString;
	}
	
	/**
	 * 时间格式转为文件名称
	 * @author xgj
	 * @param date
	 * @return
	 */
	public static String formatDateToFileName(Date date){
		if(null == date){
			return "";
		}
		SimpleDateFormat formatter = new SimpleDateFormat(getPattern(15));
		String dateString = formatter.format(date);
		return dateString;
	}
	
	/**
	 * 
	 * @author yangjiangsong
	 * @param date
	 * @return
	 */
	public static String format2Day(Date date){
		if(null == date){
			return "";
		}
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
	    String dateString = formatter.format(date);
	    return dateString;
	}
	
	
	/**
	 * 把时间差转换成时:分:秒
	 * @author yangjiangsong
	 * @param now	结束时间
	 * @param start	开始时间
	 * @return
	 */
	public static String convertDate2Hour(Date now, Date start){
		
		if(Tools.isNull(now) || Tools.isNull(start)){
//			return "00:00:00";
			return "--";
		}
		
		long secs = (now.getTime() - start.getTime()) / 1000;
		
		if(secs < 0){
			return "运行出错，请查看运行日志";
		}
		
		int hour = (int) (secs / 3600);
		int minute = (int) (secs / 60 % 60);
		int second = (int) (secs % 60);
		String hourStr = Tools.convertNuber2String(hour);
		String minuteStr = Tools.convertNuber2String(minute);
		String secondStr = Tools.convertNuber2String(second);
		
		hourStr = isNull(hourStr)? "00" : hourStr;
		minuteStr = isNull(minuteStr)? "00" : minuteStr;
		secondStr = isNull(secondStr)? "00" : secondStr;
		
		String result = hourStr + ":" + minuteStr + ":" + secondStr;
		return result;
		
	}
	
	/**
	 * 格式化展示
	 * @author yangjiangsong
	 * @param timeNumber
	 * @return
	 */
	public static String convertNuber2String(int timeNumber){
		String result = String.valueOf(timeNumber);
		switch(timeNumber){
		case 0:
			result = "00";
			break;
		case 1:
			result = "01";
			break;
		case 2:
			result = "02";
			break;
		case 3:
			result = "03";
			break;
		case 4:
			result = "04";
			break;
		case 5:
			result = "05";
			break;
		case 6:
			result = "06";
			break;
		case 7:
			result = "07";
			break;
		case 8:
			result = "08";
			break;
		case 9:
			result = "09";
			break;
		}
		return result;
	}
	
	/**
	 * 正则验证是否匹配
	 * @param str	字符串
	 * @param regEx	验证规则
	 * @return
	 * @author sf_2463(haixie) 2017年9月7日
	 */
	public static boolean regular(String str, String regEx){
		try {
			if(Tools.isNull(str) || "null".equals(str.toLowerCase())){//判断为null字符串也直接返回false
				return false;
			}
			// 编译正则表达式
			Pattern pattern = Pattern.compile(regEx);
			// 忽略大小写的写法
			Matcher matcher = pattern.matcher(str);
			// 查找字符串中是否有匹配正则表达式的字符/字符串
			return matcher.find();
		} catch (Exception e) {
			return false;//出错就返回false
		}
	}
	
	/**
	 * 把时间差转换成秒
	 * @author xgj
	 * @param start	开始时间( yyyy-MM-dd HH:mm:ss)
	 * @param end	结束时间( yyyy-MM-dd HH:mm:ss)
	 * @return
	 * @throws ParseException 
	 */
	public static String convertDate2Second(String start, String end) {
		
		String second = "s";//单位为秒
		long secs = 0L;
		if(Tools.isNull(end) || Tools.isNull(start)){
			return secs + second;
		}
		
		try {
			Date startDate = new SimpleDateFormat(getPattern(0)).parse(start);
			Date endDate = new SimpleDateFormat(getPattern(0)).parse(end);
			secs = (endDate.getTime() - startDate.getTime()) / 1000;
			if(secs < 0){
				return "时间格式错误";
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
		return secs + second;
		
	}
	
	/**
	 * 判断字符串是否json格式
	 * @param json
	 * @return
	 */
	@SuppressWarnings("resource")
	public static boolean isGoodJson(String json) {    
	        try {
				new DefaultJSONParser(json).parse();
				return true;
			} catch (Exception e) {
				return false;
			}
	}
	
}
